/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.admin.client.components;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.elf.gwt.admin.client.AdminComponentController;
import com.elf.gwt.common.client.access.RequestParameter;
import com.elf.gwt.common.client.model.ConfigurationModel;
import com.elf.gwt.common.client.model.GroupModel;
import com.elf.gwt.common.client.model.ValueModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 *  
 */
public class ConfigurationComponent extends EditTableComponent
{	
	protected static final String Zone = "Zone";
	protected List<ConfigurationModel> configurationModels;

	/**
	 * Constructor
	 */
	public ConfigurationComponent(AdminComponentController controller, String stylePrefix)
	{
		super(controller, stylePrefix);
		
		configurationModels = new ArrayList<ConfigurationModel>();
	}
	
	public void additionalRequestParameters()
	{
		addRequestParameter(new RequestParameter("configuration_group_id", selectedGroupId));
		
		if (action != null && (action.equals(Update)))
		{
			super.additionalRequestParameters();
		}
		else if (action != null & action.equals(Zone) && edit)
		{
			Iterator<String> iterElements = elements.keySet().iterator();
			while (iterElements.hasNext())
			{
				String key = iterElements.next();
				if (key.equals("STORE_COUNTRY"))
				{
					Widget widget = elements.get(key);
					String value = CommonUtils.getValue(widget);
					addRequestParameter(new RequestParameter(key, value));
					addRequestParameter(new RequestParameter("STORE_ZONE", "0"));
					addRequestParameter(new RequestParameter("action", "Update"));
					break;
				}
			}
		}
		action = "";
	}


	protected void buildMetaModel(JSONObject jsonObject) throws Exception
	{
	}

	/**
	 * BuildData from JSONArray
	 * @param jsonArray
	 */
	protected void buildModel(JSONArray jsonArray) throws Exception
	{
		configurationModels.clear();
		super.buildModel(jsonArray);
	}

	protected void buildModel(JSONObject jsonObject) throws Exception
	{
		configurationModels.add(new ConfigurationModel(jsonObject));
	}

	public void buildFromModel() throws Exception
	{
		numberOfTableEntries = configurationModels.size();
		if (edit)
			numberOfTableColumns = 3;
		else 
			numberOfTableColumns = 2;
		extraRows = 0;
		super.buildFromModel();
	}

	public void displayHeader(Grid grid) {
		grid.setText(0, 0, "Title");
		grid.setText(0, 1, "Value");
		if (edit) grid.setText(0, 2, "Description");
	}

	public void displayRow(Grid grid, int row, int entryIndex) {
		DateTimeFormat df = CommonUtils.dateTimeFormat;
		ConfigurationModel configurationModel = configurationModels.get(entryIndex);
		grid.setText(row, 0, configurationModel.getTitle());
		String value = configurationModel.getValue();
		if (edit)
		{
			Widget widget = getEditWidget(configurationModel, value);
			elements.put(configurationModel.getKey(), widget);
			grid.setWidget(row, 1, widget);

			Date dateAdded = configurationModel.getDateAdded();
			Date lastModified = configurationModel.getLastModified();
			String description = configurationModel.getDescription();
			if (dateAdded != null) description +="<br/>Date Added: " + df.format(dateAdded);
			if (lastModified != null) description +=" Last Modified: " + df.format(lastModified);
			InlineHTML descLabel = new InlineHTML(description);
			grid.setWidget(row, 2, descLabel);
		}
		else {
			String displayValue = getDisplayValue(configurationModel, value);
			grid.setText(row, 1, displayValue);
		}
	}

	protected String getDisplayValue(ConfigurationModel configurationModel, String value)
	{
		String displayValue = value;

		List<ValueModel> values = configurationModel.getValues();
		if (values != null && values.size() > 0) {
			for (Iterator<ValueModel> iter = values.iterator(); iter.hasNext(); )
			{
				ValueModel valueModel = iter.next();
				if (value.equals(valueModel.getValue())) displayValue = valueModel.getTitle();
			}
		}
		return displayValue;
	}

	protected Widget getEditWidget(ConfigurationModel configurationModel, String value)
	{
		Widget editValue = null;
		String format = configurationModel.getFormat();
		List<ValueModel> values = configurationModel.getValues();
		if (values != null && values.size() > 0) {
			ListBox listBox = new ListBox();

			int i=0;
			listBox.clear();
			for (Iterator<ValueModel> iter = values.iterator(); iter.hasNext(); )
			{
				ValueModel valueModel = iter.next();
				listBox.addItem(valueModel.getTitle(),valueModel.getValue());
				if (value.equals(valueModel.getValue()))
					listBox.setItemSelected(i, true);
				else
					listBox.setItemSelected(i, false);

				i++;
			}
			if (configurationModel.getKey().equals("STORE_COUNTRY"))
			{
				listBox.addChangeHandler(new ChangeHandler() {
					public void onChange(ChangeEvent event) {
						action = Zone;
						build(true);
					}
				});
			}
			editValue = listBox;
		}
		else if (configurationModel.getKey().equals("MASTER_PASS"))
		{
			PasswordTextBox textBox = new PasswordTextBox();
			editValue = textBox;
		}
		else if (format != null && format.equalsIgnoreCase("textarea")) {
			TextArea textArea = new TextArea();
			textArea.setText(value);
			textArea.setCharacterWidth(40);
			textArea.setVisibleLines(10);
			editValue = textArea;
		}
		else {
			TextBox textBox = new TextBox();
			textBox.setText(value);
			editValue = textBox;
		}
		return editValue;
	}

	public boolean updateFromHistoryParameters(String[] params)
	{
		boolean returnValue = super.updateFromHistoryParameters(params);
		
		if (params.length > 1)
		{
			int id = Integer.parseInt(params[1]);
			setVisible(true);
			ConfigurationGroupComponent configurationGroupComponent = (ConfigurationGroupComponent) controller.getComponent("ConfigurationGroupComponent");
			configurationGroupComponent.setSelectedGroupModel(id);
			configurationGroupComponent.setSelectedInGUI();
			adminController.getNavigationStackPanel().showStack(configurationGroupComponent.getIndex());	
			GroupModel groupModel = configurationGroupComponent.getSelectedGroupModel();
			selectedGroupId = groupModel.getId();
		}
		
		return returnValue;
	}
}
